package com.jyy.mail;

import com.jyy.server.pojo.Employee;
import com.jyy.server.pojo.MailConstants;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;


/**
 * 接收邮件
 * @author jyy
 * @since 2021-09-30
 */
@Component
public class MailReceiver {
    private static final Logger LOGGER = LoggerFactory.getLogger(MailReceiver.class);


    @Autowired
    JavaMailSenderImpl javaMailSender;
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private RedisTemplate<String ,String> redisTemplate;

    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
    public void handler(Message message, Channel channel){
        Employee employee = (Employee) message.getPayload();
        MessageHeaders headers = message.getHeaders();
        long tag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
        String msgId = ((String) headers.get("spring_returned_message_correlation"));
        HashOperations hashOperations = redisTemplate.opsForHash();

        try {
            if (hashOperations.entries("mail_log").containsKey(msgId)){
                LOGGER.error("消息已经被消费===============>{}", msgId);
                channel.basicAck(tag, false);
                return;
            }
            MimeMessage msg = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(msg);
            helper.setFrom(mailProperties.getUsername());
            helper.setTo(employee.getEmail());
            helper.setSubject("入职欢迎邮件");
            helper.setSentDate(new Date());
            Context context = new Context();
            context.setVariable("name", employee.getName());
            context.setVariable("posName", employee.getPosition().getName());
            context.setVariable("joblevelName", employee.getJoblevel().getName());
            context.setVariable("departmentName", employee.getDepartment().getName());
            String mail = templateEngine.process("mail", context);
            helper.setText(mail,true);
            javaMailSender.send(msg);
            LOGGER.info("邮件发送成功");
            hashOperations.put("mail_log", msgId, "ok");
            channel.basicAck(tag, false);
        } catch (Exception e) {
            try {
                channel.basicNack(tag, false, true);
            } catch (IOException ex) {
                LOGGER.error("邮件发送失败============>{}",e.getMessage());
            }
            LOGGER.error("邮件发送失败============>{}",e.getMessage());
        }
    }


//
//    private static final Logger LOGGER = LoggerFactory.getLogger(MailReceiver.class);
//
//    @Autowired
//    private JavaMailSender javaMailSender;
//    @Autowired
//    private MailProperties mailProperties;
//    @Autowired
//    private TemplateEngine templateEngine;
//
//    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
//    public void handler(Employee employee){
//        MimeMessage message = javaMailSender.createMimeMessage();
//        MimeMessageHelper helper = new MimeMessageHelper(message);
//        try {
//            //发件人
//            helper.setFrom(mailProperties.getUsername());
//            //收件人
//            helper.setTo(employee.getEmail());
//            //发送日期
//            helper.setSentDate(new Date());
//            //主题
//            helper.setSubject("入职信息");
//
//            //邮件内容
//            Context context = new Context();
//            context.setVariable("name",employee.getName());
//            context.setVariable("posName",employee.getPosition().getName());
//            context.setVariable("joblevelName",employee.getJoblevel().getName());
//            context.setVariable("departmentName",employee.getDepartment().getName());
//            String mail = templateEngine.process("mail", context);
//            helper.setText(mail,true);
//            javaMailSender.send(message);
//        } catch (Exception e){
//            LOGGER.error("邮件发送失败======={}",e.getMessage());
//        }
//    }
}
